package net.lab1024.sa.admin.module.business.pdf.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.business.pdf.util.OcrPerformanceMonitor;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.code.SystemErrorCode;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * PDF性能监控控制器
 *
 * @Author 1024创新实验室
 */
@Slf4j
@RestController
@RequestMapping("/pdf/performance")
@Tag(name = "PDF性能监控")
public class PdfPerformanceController {

    @Resource
    private OcrPerformanceMonitor performanceMonitor;

    @GetMapping("/report")
    @Operation(summary = "获取OCR性能报告")
    public ResponseDTO<Map<String, Object>> getPerformanceReport() {
        try {
            Map<String, Object> report = performanceMonitor.getStrategyPerformanceReport();
            return ResponseDTO.ok(report);
        } catch (Exception e) {
            log.error("获取性能报告失败: {}", e.getMessage());
            return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR, "获取性能报告失败: " + e.getMessage());
        }
    }

    @GetMapping("/suggestions")
    @Operation(summary = "获取优化建议")
    public ResponseDTO<List<String>> getOptimizationSuggestions() {
        try {
            List<String> suggestions = performanceMonitor.getOptimizationSuggestions();
            return ResponseDTO.ok(suggestions);
        } catch (Exception e) {
            log.error("获取优化建议失败: {}", e.getMessage());
            return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR, "获取优化建议失败: " + e.getMessage());
        }
    }

    @GetMapping("/best-strategy")
    @Operation(summary = "获取最佳策略建议")
    public ResponseDTO<Map<String, Object>> getBestStrategy(@RequestParam String imageQuality) {
        try {
            String bestStrategy = performanceMonitor.getBestStrategyForQuality(imageQuality);
            Map<String, Object> result = new HashMap<>();
            result.put("imageQuality", imageQuality);
            result.put("recommendedStrategy", bestStrategy);
            return ResponseDTO.ok(result);
        } catch (Exception e) {
            log.error("获取最佳策略失败: {}", e.getMessage());
            return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR, "获取最佳策略失败: " + e.getMessage());
        }
    }

    @GetMapping("/stats")
    @Operation(summary = "获取统计信息")
    public ResponseDTO<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> report = performanceMonitor.getStrategyPerformanceReport();
            
            // 提取关键统计信息
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalPages", report.get("totalPages"));
            stats.put("successfulPages", report.get("successfulPages"));
            stats.put("overallSuccessRate", report.get("overallSuccessRate"));
            
            // 策略统计
            @SuppressWarnings("unchecked")
            Map<String, Object> strategyStats = (Map<String, Object>) report.get("strategyStats");
            if (strategyStats != null) {
                stats.put("strategyCount", strategyStats.size());
                
                // 找出最佳策略
                String bestStrategy = strategyStats.entrySet().stream()
                        .max((e1, e2) -> {
                            double rate1 = (Double) ((Map<String, Object>) e1.getValue()).get("successRate");
                            double rate2 = (Double) ((Map<String, Object>) e2.getValue()).get("successRate");
                            return Double.compare(rate1, rate2);
                        })
                        .map(Map.Entry::getKey)
                        .orElse("无");
                
                stats.put("bestStrategy", bestStrategy);
            }
            
            return ResponseDTO.ok(stats);
        } catch (Exception e) {
            log.error("获取统计信息失败: {}", e.getMessage());
            return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR, "获取统计信息失败: " + e.getMessage());
        }
    }
} 